package mspbots.next.ticket.core.data.rules;

import lombok.RequiredArgsConstructor;
import mspbots.next.ticket.core.AbstractToolsUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.stream.Collectors;

/**
 * com.mspbots.ticket.core.rules.RuleServiceImpl
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2020/4/24
 */
@Service
@RequiredArgsConstructor
public class RulesServiceImpl extends AbstractToolsUtil {

    private final RulesRepository rulesRepository;

    public Flux<Rule> findByTenant(Long tenantId) {
        return this.rulesRepository.findByTenantId(tenantId);
    }
    public Flux<Rule> findByEnable(Long tenantId) {
        return this.findByTenant(tenantId)
                .filter(Rule::getEnable);
    }

    public Mono<Rule> saveOne(Long tenantId, RuleRequest request) {

        Rule rule = new Rule();
        rule.setTenantId(tenantId);
        BeanUtils.copyProperties(request, rule);
        return this.rulesRepository.save(rule);

    }

    public Flux<Rule> batchSave(Long tenantId, List<RuleRequest> requests) {

        List<Rule> rules = requests.parallelStream().map(request -> {
            Rule rule = new Rule();
            rule.setTenantId(tenantId);
            BeanUtils.copyProperties(request, rule);
            return rule;
        }).collect(Collectors.toList());
        return this.rulesRepository.saveAll(rules);

    }

}
